<template>
  <div class="dashboard-container">
    <!-- 统计卡片区域 -->
    <div class="stats-grid">
      <!-- 本月统计卡片 -->
      <div class="stat-card monthly-stats">
        <div class="stat-card-content">
          <div class="stat-icon">
            <el-icon>
              <Calendar/>
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">本月成功天数</div>
            <div class="stat-value">{{ monthlyStats.successDays }}天</div>
            <el-progress
                :percentage="monthlyStats.successRate"
                :format="format => `${format}%`"
                :stroke-width="8"
                class="stat-progress"
                :color="['#10B981', '#34D399']"
            />
          </div>
        </div>
      </div>

      <!-- 累计统计卡片 -->
      <div class="stat-card total-stats">
        <div class="stat-card-content">
          <div class="stat-icon">
            <el-icon>
              <Trophy/>
            </el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-label">累计早睡天数</div>
            <div class="stat-value">{{ totalStats.successDays }}天</div>
          </div>
          <div class="points-info">
            <div class="points-value">{{ totalStats.availablePoints }}</div>
            <div class="points-label">可用积分</div>
          </div>
          <el-button type="primary" class="exchange-btn" @click="$router.push('/shop')">
            <el-icon>
              <ShoppingCart/>
            </el-icon>
            立即兑换
          </el-button>
        </div>
      </div>
    </div>

    <!-- 打卡日历区域 -->
    <div class="calendar-section">
      <div class="calendar-header">
        <div class="calendar-header-left">
          <h2 class="calendar-title">打卡日历</h2>
          <div class="month-display">
            <span class="current-month">{{ currentYear }}年{{ currentMonth }}月</span>
            <el-button
                class="today-button"
                size="small"
                @click="goToCurrentMonth"
            >
              今
            </el-button>
          </div>
        </div>
      </div>

      <div class="calendar-grid">
        <div class="calendar-weekdays">
          <span v-for="day in ['日', '一', '二', '三', '四', '五', '六']" :key="day">
            {{ day }}
          </span>
        </div>
        <div class="calendar-days">
          <div
              v-for="day in calendarDays"
              :key="day.date"
              :class="[
              'calendar-day',
              { 
                'success': isSuccessDay(day),
                'fail': isFailDay(day),
                'today': isToday(day.date),
                'other-month': !day.isCurrentMonth
              }
            ]"
              @click="handleDayClick(day)"
          >
            {{ day.dayNumber }}
            <div v-if="isSuccessDay(day)" class="day-status-dot success"></div>
            <div v-if="isFailDay(day)" class="day-status-dot fail"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.dashboard-container {
  max-width: 100%;
  margin: 0;
  padding: 0;
  background: #F8FAFC;
  min-height: 100vh;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
  gap: 24px;
  margin: 24px;
}

.stat-card {
  background: linear-gradient(135deg, #FFFFFF 0%, #F8FAFC 100%);
  border-radius: 20px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  border: 1px solid rgba(226, 232, 240, 0.8);
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.stat-card-content {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #10B981 0%, #34D399 100%);
  color: white;
  font-size: 24px;
  margin-bottom: 8px;
}

.stat-info {
  flex-grow: 1;
}

.stat-label {
  font-size: 16px;
  color: #64748B;
  font-weight: 500;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #1E293B;
  margin-bottom: 16px;
}

.stat-progress {
  margin-top: 8px;
}

.points-info {
  background: linear-gradient(135deg, #F1F5F9 0%, #F8FAFC 100%);
  border-radius: 16px;
  padding: 20px;
  text-align: center;
  border: 1px solid rgba(226, 232, 240, 0.6);
}

.points-value {
  font-size: 36px;
  font-weight: 800;
  background: linear-gradient(135deg, #10B981 0%, #34D399 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin-bottom: 8px;
}

.points-label {
  font-size: 16px;
  color: #64748B;
  font-weight: 500;
}

.exchange-btn {
  width: 100%;
  border-radius: 12px;
  font-weight: 600;
  height: 44px;
  font-size: 16px;
  background: linear-gradient(135deg, #10B981 0%, #34D399 100%);
  border: none;
  margin-top: 16px;
  transition: all 0.3s ease;
}

.exchange-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(16, 185, 129, 0.2);
}

.calendar-section {
  background: white;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(226, 232, 240, 0.8);
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px;
  background: #F8FAFC;
  border-radius: 16px;
  border: 1px solid rgba(226, 232, 240, 0.6);
}

.calendar-header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.calendar-title {
  font-size: 20px;
  font-weight: 700;
  color: #1E293B;
  margin: 0;
}

.month-display {
  display: flex;
  align-items: center;
  gap: 8px;
  background: white;
  padding: 8px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(226, 232, 240, 0.6);
}

.current-month {
  font-size: 15px;
  font-weight: 600;
  color: #64748B;
}

.today-button {
  background: #10B981;
  border: none;
  color: white;
  padding: 6px 12px;
  border-radius: 8px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.today-button:hover {
  background: #059669;
  transform: translateY(-1px);
}

.calendar-grid {
  background: #F8FAFC;
  border-radius: 16px;
  padding: 20px;
  border: 1px solid rgba(226, 232, 240, 0.6);
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  font-weight: 600;
  color: #64748B;
  margin-bottom: 12px;
  font-size: 14px;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8px;
}

.calendar-day {
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 500;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
  color: #1E293B;
  border: 1px solid rgba(226, 232, 240, 0.6);
  position: relative;
}

.calendar-day:hover:not(.disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.calendar-day.success {
  background: #ECFDF5;
  color: #059669;
  border-color: #34D399;
}

.calendar-day.fail {
  background: #FEF2F2;
  color: #DC2626;
  border-color: #F87171;
}

.calendar-day.today {
  background: #10B981;
  color: white;
  border-color: #059669;
  font-weight: 700;
}

.calendar-day.other-month {
  color: #94A3B8;
  background: #F1F5F9;
}

.day-status-dot {
  position: absolute;
  bottom: 4px;
  right: 4px;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  display: block;
}

.day-status-dot.success {
  background-color: #10B981;
}

.day-status-dot.fail {
  background-color: #DC2626;
}

@media screen and (max-width: 768px) {
  .dashboard-container {
    padding: 16px;
  }

  .stats-grid {
    grid-template-columns: 1fr;
    gap: 16px;
    margin-bottom: 24px;
  }

  .stat-card-content {
    padding: 20px;
  }

  .stat-value {
    font-size: 28px;
  }

  .points-value {
    font-size: 32px;
  }

  .calendar-section {
    padding: 16px;
  }

  .calendar-header {
    padding: 12px;
    flex-direction: column;
    gap: 12px;
  }

  .calendar-header-left {
    width: 100%;
    justify-content: space-between;
  }

  .calendar-title {
    font-size: 18px;
  }

  .month-display {
    padding: 6px 12px;
  }

  .current-month {
    font-size: 14px;
  }

  .calendar-grid {
    padding: 12px;
  }

  .calendar-day {
    font-size: 13px;
  }
}
</style>

<script setup>
import {computed, onMounted, ref, watch} from 'vue'
import {Calendar, ShoppingCart, Trophy} from '@element-plus/icons-vue'
import {useTokenStore} from '@/stores/token'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {useApi} from "@/api/dashboard";

const tokenStore = useTokenStore()
const router = useRouter()

const monthlyStats = ref({
  successDays: 0,
  successRate: 0
})

const totalStats = ref({
  successDays: 0,
  availablePoints: 0
})

const currentMonth = ref(new Date().getMonth() + 1)
const currentYear = ref(new Date().getFullYear())
const checkInRecords = ref([])
const successDays = ref([])

const handleDayClick = (day) => {
  if (!day.isCurrentMonth) {
    currentMonth.value = day.date.getMonth() + 1
    currentYear.value = day.date.getFullYear()
  }
}

const isCurrentMonth = computed(() => {
  const today = new Date()
  return currentMonth.value === today.getMonth() + 1 && currentYear.value === today.getFullYear()
})

const changeMonth = (delta) => {
  let newMonth = currentMonth.value + delta
  let newYear = currentYear.value

  if (newMonth > 12) {
    newMonth = 1
    newYear++
  } else if (newMonth < 1) {
    newMonth = 12
    newYear--
  }

  currentMonth.value = newMonth
  currentYear.value = newYear
}

// 添加触摸滑动处理
let touchStartX = 0
let touchStartY = 0

onMounted(() => {
  const calendarSection = document.querySelector('.calendar-section')
  if (calendarSection) {
    calendarSection.addEventListener('touchstart', handleTouchStart)
    calendarSection.addEventListener('touchmove', handleTouchMove)
  }
})

const handleTouchStart = (event) => {
  touchStartX = event.touches[0].clientX
  touchStartY = event.touches[0].clientY
}

const handleTouchMove = (event) => {
  if (!touchStartX || !touchStartY) return

  const touchEndX = event.touches[0].clientX
  const touchEndY = event.touches[0].clientY

  const deltaX = touchEndX - touchStartX
  const deltaY = touchEndY - touchStartY

  // 确保水平滑动距离大于垂直滑动距离，避免与页面滚动冲突
  if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > 50) {
    if (deltaX > 0) {
      changeMonth(-1) // 向右滑动，显示上个月
    } else {
      changeMonth(1) // 向左滑动，显示下个月
    }
    touchStartX = 0
    touchStartY = 0
  }
}

const goToCurrentMonth = () => {
  const today = new Date()
  currentMonth.value = today.getMonth() + 1
  currentYear.value = today.getFullYear()
}

const calendarDays = computed(() => {
  const days = []
  const firstDay = new Date(currentYear.value, currentMonth.value - 1, 1)
  const lastDay = new Date(currentYear.value, currentMonth.value, 0)

  // 获取上个月的最后几天
  const prevMonthLastDay = new Date(currentYear.value, currentMonth.value - 1, 0)
  const firstDayWeekDay = firstDay.getDay()

  for (let i = firstDayWeekDay - 1; i >= 0; i--) {
    days.push({
      date: new Date(currentYear.value, currentMonth.value - 2, prevMonthLastDay.getDate() - i),
      dayNumber: prevMonthLastDay.getDate() - i,
      isCurrentMonth: false
    })
  }

  // 当前月的天数
  for (let i = 1; i <= lastDay.getDate(); i++) {
    days.push({
      date: new Date(currentYear.value, currentMonth.value - 1, i),
      dayNumber: i,
      isCurrentMonth: true
    })
  }

  // 下个月的开始几天
  const remainingDays = 42 - days.length // 保持6行7列的日历格式
  for (let i = 1; i <= remainingDays; i++) {
    days.push({
      date: new Date(currentYear.value, currentMonth.value, i),
      dayNumber: i,
      isCurrentMonth: false
    })
  }

  return days
})

const fetchDashboardData = async () => {
  try {
    const response = await useApi.dashboard()
    monthlyStats.value = response.data.monthlyStats
    totalStats.value = response.data.totalStats
    checkInRecords.value = response.data.checkInRecords

  } catch (error) {
    ElMessage.error('获取数据失败')
  }
}

onMounted(async () => {
  await fetchDashboardData()
})

const isFailDay = (day) => {
  if (!day.isCurrentMonth) return false
  const dateStr = `${currentYear.value}-${String(currentMonth.value).padStart(2, '0')}-${String(day.dayNumber).padStart(2, '0')}`
  return checkInRecords.value.some(record => record.date === dateStr && record.status === 'fail')
}

const isSuccessDay = (day) => {
  if (!day.isCurrentMonth) return false
  const dateStr = `${currentYear.value}-${String(currentMonth.value).padStart(2, '0')}-${String(day.dayNumber).padStart(2, '0')}`
  return checkInRecords.value.some(record => record.date === dateStr && record.status === 'success')
}

const isToday = (date) => {
  const today = new Date()
  return date.getFullYear() === today.getFullYear() &&
      date.getMonth() === today.getMonth() &&
      date.getDate() === today.getDate()
}

watch(currentMonth, () => {
  fetchDashboardData()
})

onMounted(() => {
  fetchDashboardData()
})
</script>